package com.ipt.frm.pw.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ipt.frm.bean.Mensaje;
import com.ipt.frm.enumeracion.TipoMensaje;

public class FiltroUsuario extends FiltroMaestro {
	ArrayList<String> urlList = null;

	/**
	 * @see: 
	 *       http://viralpatel.net/blogs/http-session-handling-tutorial-using-servlet
	 *       -filters-session-error-filter-servlet-filter/
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession session = httpRequest.getSession();
		// ServletContext application =;

		// Comprobar que existe un usuario en session en caso contrario de no
		// existir forward al login
		/*
		 * InputStream stream = application
		 * .getResourceAsStream("/WEB-INF/config/messages.properties");
		 * Properties props = new Properties(); props.load(stream);
		 */
		String url = httpRequest.getServletPath().toString();
		boolean allowedRequest = false;

		if (urlList.contains(url)) {
			allowedRequest = true;
		}

		if (!allowedRequest) {
			if (null == session.getAttribute("username")) {
				Mensaje mensaje = new Mensaje(TipoMensaje.ERROR,
						"[filter] Para acceder a la app debe iniciar sesion");
				httpRequest.setAttribute("MSG", mensaje);
				httpRequest.setAttribute("title", "Login");
				httpRequest.getRequestDispatcher("/login.jsp").forward(request,
						response);
			} else {
				httpRequest.setAttribute("title", "Login");
			}

		}
		/*
		 * if (null == session.getAttribute("username")) { // dispatcher =
		 * request.getRequestDispatcher("login.jsp"); // msg error Mensaje
		 * mensaje = new Mensaje(TipoMensaje.ALERT,
		 * "[filter] Para acceder a la app debe iniciar sesion");
		 * request.setAttribute("MSG", mensaje); request.setAttribute("title",
		 * "Login"); request.getRequestDispatcher("/login.jsp").forward(request,
		 * response);
		 * 
		 * }
		 */
		super.doFilter(request, response, chain);
	}

	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		String urls = fConfig.getInitParameter("no-avoid-urls");
		StringTokenizer token = new StringTokenizer(urls, ",");

		urlList = new ArrayList<String>();

		while (token.hasMoreTokens()) {
			urlList.add(token.nextToken());

		}
	}
}
